﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using Xceed.Silverlight.Data;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Xceed.Silverlight.ListBox
{
  public class GroupDataContext : INotifyPropertyChanged
  {
    internal GroupDataContext( DataPath dataPath, ObservableCollection<GroupDescription> groupDescriptions )
    {
      if( dataPath == null )
        throw new ArgumentNullException( "dataPath" );

      if( groupDescriptions == null )
        throw new ArgumentNullException( "groupDescriptions" );

      m_dataPath = dataPath;
      m_groupDescriptions = groupDescriptions;

      this.BuildGroupValueDescriptionList();
    }

    #region DataPath Read-Only Internal Property

    internal DataPath DataPath
    {
      get
      {
        return m_dataPath;
      }
    }


    #endregion

    #region GroupValue Read-Only Property

    public object GroupValue
    {
      get
      {
        DataPath dataPath = this.DataPath;

        if( dataPath == null )
          throw new ListBoxInternalException( "No DataPath accessible for a GroupDataContext." );

        return dataPath.LastChild.Data;
      }
    }

    #endregion

    #region LeafValue Read-Only Property
    public object LeafValue
    {
      get
      {
        if( this.FieldNameValuePairs == null )
          throw new ListBoxInternalException( "FieldNameValuePairs is null." );

        return this.FieldNameValuePairs.Last().Value;
      }
    }
    #endregion

    #region RootValue Read-Only Property
    public object RootValue
    {
      get
      {
        if( this.FieldNameValuePairs == null )
          throw new ListBoxInternalException( "FieldNameValuePairs is null." );

        return this.FieldNameValuePairs.First().Value;
      }
    }
    #endregion

    #region FieldNameValuePairs Read-Only Property
    public List<FieldNameValuePair> FieldNameValuePairs
    {
      get
      {
        return m_fieldNameValuePairs;
      }
    }
    #endregion

    // Override ToString to be able to use {Binding}
    // directly in DataTemplate to display the GroupValue
    public override string ToString()
    {
      object groupValue = this.GroupValue;

      return (groupValue == null)
        ? string.Empty
        : groupValue.ToString();
    }

    #region Private Methods

    private IEnumerator GetEnumerator()
    {
      DataPath dataPath = m_dataPath;

      if( dataPath == null )
        throw new ListBoxInternalException( "No DataPath accessible for a GroupDataContext" );

      return dataPath.Select( this.DataItemToDataConverter ).GetEnumerator();
    }

    private object DataItemToDataConverter( DataItem dataItem )
    {
      if( dataItem == null )
        return null;

      // Return null if not loaded to avoid displaying
      // invalid data in async scenarios
      if( !dataItem.IsLoaded )
        return null;

      return dataItem.Data;
    }

    void BuildGroupValueDescriptionList()
    {
      m_fieldNameValuePairs = new List<FieldNameValuePair>();

      // Get the DataPath group values
      IEnumerator enumerator = this.GetEnumerator();

      if( enumerator == null )
        throw new ListBoxInternalException( "Enumerator is null." );

      // Fill the value List
      int groupDescriptionIndex = 0;
      object value = null;
      string fieldName = null;
      FieldNameValuePair groupValue = null;

      // Process each group value
      while( enumerator.MoveNext() )
      {
        if( ( groupDescriptionIndex < 0 ) || ( groupDescriptionIndex >= m_groupDescriptions.Count ) )
          break;

        value = enumerator.Current;

        // Find the associate group description field name
        fieldName = m_groupDescriptions.ElementAt( groupDescriptionIndex ).GetPropertyName();

        // Create the FieldNameValuePair
        groupValue = new FieldNameValuePair( value, fieldName );

        // Identify leaf and root GroupValue 
        // We need two different condition here (no else) because
        // a groupValue can be a Leaf and a root at the same time.
        if( groupDescriptionIndex == 0 )
        {
          groupValue.IsRoot = true;
        }

        if( groupDescriptionIndex == ( m_groupDescriptions.Count - 1 ) )
        {
          groupValue.IsLeaf = true;
        }

        // Add it to the list
        m_fieldNameValuePairs.Add( groupValue );
        groupDescriptionIndex++;
      }
    }

    #endregion


    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged( string propertyName )
    {
      if( propertyName == null )
        propertyName = string.Empty;

      if( this.PropertyChanged == null )
        return;

      this.PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
    }

    #endregion


    #region Private Members
    private DataPath m_dataPath;
    private List<FieldNameValuePair> m_fieldNameValuePairs;
    private ObservableCollection<GroupDescription> m_groupDescriptions;
    #endregion

  }
}
